#pragma once
#include <iostream>
#include <functional>
#include <condition_variable>
#include <vector>
#include <thread>
#include <atomic>
#include <mutex>
#include <future>

using std::vector;
using std::thread;
using std::atomic;
using std::mutex;
using std::condition_variable;

class threadpool
{
    using TaskType = std::function<void(void)>;
public:
    threadpool(int thread_count = 1): _stop(false)
    {
        for(int i = 0; i < thread_count; ++i)
        {
            _threads.emplace_back(&threadpool::entry, this);
        }
    }
    ~threadpool()
    {
        stop();
    }

    void stop()
    {
        if(_stop) return;
        
        _stop = true;
        _cv.notify_all();
        for(auto& thread : _threads)
        {
            thread.join();
        }
    }

    // 向线程池中丢任务的接口
    template<typename F, typename ...Args>
    auto push(F&& func, Args&& ...args) -> std::future<decltype(func(args...))>
    {
        // 1.将传入函数封装成packaged_task对象/指针
        using return_type = decltype(func(args...));
        auto function = std::bind(std::forward<F>(func), std::forward<Args>(args)...);
        auto ptask = std::make_shared<std::packaged_task<return_type()>>(function);

        auto fu = ptask->get_future();
        // 2.构建lambda对象，将捕获的task对象在函数内执行，并将匿名lambda对象丢入任务池_taskpool
        {
            std::unique_lock<mutex> lock(_mutex);
            _taskpool.push_back( [ptask](){ (*ptask)(); } );
            _cv.notify_one();   // 唤醒一个线程来执行
        }
        return fu;
    }

private:
    // 线程入口函数，内部不断从任务池中取出任务执行
    void entry()
    {
        while(!_stop)
        {
            auto tmp_taskpool = _taskpool;
            tmp_taskpool.clear();
            {
                // 1.加锁
                std::unique_lock<mutex> lock(_mutex);
                // At the moment of blocking the thread, the function automatically calls lck.unlock()
                // 被通知后重新检查谓词，如果谓词仍然为假，会继续阻塞直到谓词为真
                _cv.wait(lock, [this]() -> bool{ return _stop || !_taskpool.empty(); } );
                // 2.取出任务后续执行
                _taskpool.swap(tmp_taskpool);
            }
            
            for(auto& task: tmp_taskpool)
            {
                task();
            }
        }
    }
private:
    atomic<bool> _stop;
    vector<TaskType> _taskpool;
    mutex _mutex;
    condition_variable _cv;
    vector<thread> _threads;
};

